package com.xaptul.docpreview.util.converter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xaptul.docpreview.util.abstra.Converter;
import com.xaptul.docpreview.util.exception.ConvertException;

@Supported({ "*.ppt", "*.pps", "*.pptx", "*.pptm" })
public class PptConverter implements Converter {

	private Logger logger = LoggerFactory.getLogger(PptConverter.class);

	private Jodconverter jodconverter;

	public PptConverter(Jodconverter jodconverter) {
		this.jodconverter = jodconverter;
	}

	public void convert(File infile, File outfile) throws ConvertException {
		if (outfile.exists())
			return;
		this.jodconverter.convert(infile, outfile);

		File outdir = outfile.getParentFile();
		File[] files = outdir.listFiles();
		File[] imgs = new File[files.length];
		String filename;
		for (File file : files) {
			filename = file.getName();
			if (filename.toLowerCase().endsWith(".jpg")) {
				int idx = Integer.parseInt(filename.substring(3,
						filename.length() - 4));
				imgs[idx] = file;
			} else {
				// file.delete(); //除了生成的图片以外的都删除
			}
		}
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(outfile);
			fileWriter.write("<!DOCTYPE html>\n");
			fileWriter.write("<html>\n");
			fileWriter
					.write("<head><meta HTTP-EQUIV=CONTENT-TYPE CONTENT=\"text/html; charset=utf-8\"></head>\n");
			fileWriter.write("<body>\n");
			for (File f : imgs)
				if (f != null) {
					fileWriter.write("<center><img src=\"");
					fileWriter.write(f.getName());
					fileWriter.write("\"></center>\n");
				}
			fileWriter.write("</body>\n");
			fileWriter.write("</html>\n");
		} catch (IOException e) {
			throw new ConvertException(e);
		} finally {
			if (fileWriter != null)
				try {
					fileWriter.close();
				} catch (IOException e) {
					this.logger.error(e.getMessage(), e);
				}
		}
	}
}